﻿// Copyright (C) 2012 Kim Jensen, TaskJunction.com
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TaskJunctionLib.Model;
using TaskJunctionLib.Communication;
using TaskJunctionLib.Mapping;
using System.ComponentModel;

namespace TaskJunctionLib.Repository
{
    public abstract class Repository<T, TMapper> : IRepository<T, TMapper>
        where T : ModelEntity
        where TMapper : IObjectMapper<T>, new()
    {
        public Repository()
        {
            mapper = new TMapper();
        }

        public Client Client { get; set; }
        private TMapper mapper;

        public virtual T Load(int id)
        {
            return mapper.deserialize(Client.Get(GetObjectResourceName(id)));
        }

        public virtual void Save(T obj)
        {
            var data = mapper.serialize(obj);
            var retval = (obj.Id == null) ? Client.Post(GetResourceName(), data) : Client.Put(GetObjectResourceName(obj.Id), data);

            if (!String.IsNullOrEmpty(retval))
            {
                mapper.deserialize(retval, obj);
            }
        }

        public virtual void Delete(T obj)
        {
            Client.Delete(GetObjectResourceName(obj.Id));
        }

        protected abstract string GetResourceName();

        protected string GetObjectResourceName(int? id)
        {
            return GetResourceName() + ((id == null) ? "" : "/" + id);
        }

        protected string GetResourceNameByValues(Dictionary<string, string> map)
        {
            return GetResourceName() + "?" + String.Join("&", map.Where(x => x.Value != null).Select(x => x.Key + "=" + x.Value));
        }

        protected virtual IList<T> _LoadList(string resourceName)
        {
            return mapper.deserializeList(Client.Get(resourceName));
        }
    }
}
